package com.datastructure.test.findnthdigit;

public class FindNthDigit {

    public static void main(String[] args) {
        FindNthDigit findNthDigit = new FindNthDigit();
        int nthDigit = findNthDigit.findNthDigit(1000000000);
        System.out.println(nthDigit);
    }

    public int findNthDigit (int n) {
        // write code here
        if (n <= 0) return 0;
        long start = 1, digit = 1, count = 9;
        while (n > count) {
            n -= count; // 减去当前位数的总长度
            start *= 10;
            digit++;
            count = start * 9 * digit;
        }
        // 找到当前位数的区间了
        String num = (start + (n - 1) / digit) + ""; // 减去第0号元素0
        int idx = (int) ((n - 1) % digit);
        return num.charAt(idx) - 48;
    }
}
